#!/bin/bash
#============================================================
# build-ollama-vulkan.sh
# 用途：在 root SSH 环境下部署支持 Vulkan 的 Ollama
# 无需 sudo，直接执行
#============================================================

set -euo pipefail

# -------------------------------
# 配置
# -------------------------------
BINARY_URL="https://github.com/itzg/ollama-docker/releases/download/v0.12.9/ollama-linux-amd64-vulkan"
TEMP_FILE="/tmp/ollama-linux-amd64-vulkan"
OLLAMA_BIN="/usr/local/bin/ollama"
SERVICE_D_DIR="/etc/systemd/system/ollama.service.d"
VULKAN_CONF="$SERVICE_D_DIR/vulkan.conf"

# -------------------------------
# 1. 停止 Ollama 服务和进程
# -------------------------------
echo "🛑 停止 Ollama 服务..."
systemctl stop ollama || true

# -------------------------------
# 2. 下载支持 Vulkan 的二进制
# -------------------------------
echo "⬇️ 下载支持 Vulkan 的 Ollama: $BINARY_URL"
rm -f "$TEMP_FILE"
wget -O "$TEMP_FILE" "$BINARY_URL" || {
    echo "❌ 下载失败，请检查网络"
    exit 1
}

cp "$TEMP_FILE" "$OLLAMA_BIN"
chmod +x "$OLLAMA_BIN"
echo "✅ 已安装新版本到 $OLLAMA_BIN"

# -------------------------------
# 3. 配置 Vulkan 环境变量
# -------------------------------
mkdir -p "$SERVICE_D_DIR"

cat << EOF > "$VULKAN_CONF"
[Service]
Environment=GGML_VULKAN=1
Environment=OLLAMA_FLASH_ATTENTION=1
Environment=OLLAMA_HOST=0.0.0.0:11434
Environment=OLLAMA_MODELS=/data/ollama
EOF

echo "✅ Vulkan 环境已配置"

# -------------------------------
# 4. 启动服务
# -------------------------------
echo "🔄 启动 Ollama 服务..."
systemctl daemon-reexec
systemctl enable ollama --now
systemctl restart ollama

# -------------------------------
# 5. 显示日志
# -------------------------------
echo ""
echo "🎉 部署完成！正在查看日志..."
sleep 3
journalctl -u ollama -n 20 --no-pager